import {
  Scene,
  Engine,
  CubeTexture,
  FreeCamera,
  Vector3,
   MeshBuilder,
  SceneLoader,
  HemisphericLight,
  PhysicsImpostor,
  AnimationGroup,
  AbstractMesh,
  Material,
  WebXRControllerComponent,
  WebXRDefaultExperience,
  WebXRSessionManager
} from "@babylonjs/core";
import {  StackPanel} from '@babylonjs/gui/2D';
import "@babylonjs/loaders";
export class XR_demo_one {
  scene!: Scene;
  engine!: Engine;
  camera!: FreeCamera;
  characterAnimations!: AnimationGroup[]
  panel!: StackPanel;
  handleMesh!:AbstractMesh | null;
  triggerComponent_!: WebXRControllerComponent
  xrHelper_!: WebXRDefaultExperience
  sessionManager!: WebXRSessionManager
   constructor() {

  
  }
  init(canvas: HTMLCanvasElement){

    this.engine = new Engine(canvas, true);
    this.scene = this.CreateScene(canvas);  // 天空盒
    this.sessionManager = new WebXRSessionManager(this.scene);
    // eslint-disable-next-line @typescript-eslint/no-this-alias
   // eslint-disable-next-line no-unexpected-multiline
    this.CreateMesh()
    this.CreateBarrel()
    this.CreateSupported
    this.engine.runRenderLoop(() => {
      this.scene.render(); // 渲染到场景中
    });

  }
  get_handleMesh(){
    console.log(0)
    return this.handleMesh
  }
  CreateScene(canvas: HTMLCanvasElement): Scene {
    const scene = new Scene(this.engine);
    
    const envTex = CubeTexture.CreateFromPrefilteredData(
      './1k.env',
      scene
    );

    scene.environmentTexture = envTex;


    scene.environmentIntensity = 0.5;

    scene.createDefaultSkybox(envTex, true, 10000,1);






    const camera = new FreeCamera('camera',new Vector3(5,5,0),scene); // create a free camera
    camera.attachControl(canvas,true)

    camera.minZ =0.45 ; //定义相机可以看到的最小距离。值得注意的是，深度缓冲区并不是无限的，它开始得越近，场景就越可能遇到深度对抗问题。 (设置最小剪辑 值 )
    camera.speed =0.5 ; //定义相机的当前速度
    camera.angularSensibility =6000 //获取鼠标输入的输入灵敏度。（默认值为2000.0）值越高，灵敏度越低。设置鼠标输入的输入灵敏度。（默认值为2000.0）值越高，灵敏度越低。
    camera.keysUp.push(87); //获取或设置用于控制相机向前移动的键盘键列表。
    camera.keysLeft.push(65); //获取或设置用于控制相机向左扫射的键盘键列表。
    camera.keysDown.push(83);//获取或设置用于控制相机向后移动的键盘键列表。
    camera.keysRight.push(68); //获取或设置用于控制相机向右扫射的键盘键列表。

      //设置鼠标敏感度
    camera.angularSensibility = 500;

    canvas.addEventListener('click', this.canvasClick);




    return scene;
  }
  canvasClick():void{
    console.log(' 点击画布')
  }
  // 异步加载模型演示    
  async CreateBarrel(): Promise<void> {
    // const light =  new HemisphericLight("HemiLight", new Vector3(0, 1, 0), this.scene);
    // light.intensity=0.1
    // this.sphere =   MeshBuilder.CreateSphere("sphere1", { diameter: 10 }, this.scene);
  




      const { meshes ,animationGroups} = await SceneLoader.ImportMeshAsync('', './', 'B工厂08.10版(无地贴，去掉白模.glb',this.scene)


    const qiying =  await SceneLoader.ImportMeshAsync('', './', 'qiying.glb',this.scene)
    const qiyingMesh = qiying.meshes[0]
    qiyingMesh.scaling =  new Vector3(11, 11, 11)
    qiyingMesh.position.x =-40
    qiyingMesh.position.y =-5
    qiyingMesh.position.z =-3
    qiyingMesh.rotate( new Vector3(0,1,0), -Math.PI/2)
    const zombie =  await SceneLoader.ImportMeshAsync('', './', 'zombie-girl.glb',this.scene)

     const zombieGirl = zombie.meshes[0]

     zombieGirl.position.x =-40
     zombieGirl.position.z =-10
     zombieGirl.position.y =-1
   
        animationGroups.forEach(item=>item.play(true))
      meshes[0].position.y = -5
       meshes.map(mesh=>{
          mesh.checkCollisions = true //获取或设置一个布尔值，该布尔值指示此网格可以在冲突引擎中使用
       })
  }
  async CreateSupported():Promise<void>{
    const supported = await this.sessionManager.isSessionSupportedAsync('immersive-vr'); //检查指定的创建选项是否支持会话 是否支持XR 会话
    if (supported) {
        console.log(
            '会话机制？？',supported
        )
        this.sessionManager.initializeSessionAsync('immersive-vr' /*, xrSessionInit */ ); //初始化xr会话(此函数将初始化本机会话。如果不调用此函数，则没有可用的会话，并且 XR 体验将不起作用。)
        const referenceSpace = this.sessionManager.setReferenceSpaceTypeAsync( /*referenceSpaceType = 'local-floor'*/ ); //设置xr会话上的参考空间
        const renderTarget = this.sessionManager.getWebXRRenderTarget( /*outputCanvasOptions: WebXRManagedOutputCanvasOptions*/ );
        const xrWebGLLayer = renderTarget.initializeXRLayerAsync(this.sessionManager.session);

        this.sessionManager.runXRRenderLoop();

      this.sessionManager.onXRFrameObservable.add(xx=>{
        console.log(xx,'1111111111111111')
    })
    }

   
  }


  async CreateMesh(): Promise<void>  {



    const ground = MeshBuilder.CreateGround("ground", { width: 1000, height: 1000 }, this.scene);
    ground.physicsImpostor = new PhysicsImpostor(ground, PhysicsImpostor.BoxImpostor, { mass: 0, friction: 0.8, restitution: 0.5, disableBidirectionalTransformation: true }, this.scene);
    ground.checkCollisions = true;
    ground.position.y = -5.1;
    ground.material= new Material("mat", this.scene); // 透明材质 （这个地板是为了增加移动，添加物理引擎）
  
    const light = new HemisphericLight("light", new Vector3(0, 1, 0), this.scene);
    light.intensity = 0.7;

    // this.scene.createDefaultEnvironment();
    this.xrHelper_ = await this.scene.createDefaultXRExperienceAsync({
        floorMeshes: [ground] // 地板增加物理引擎
    });

    this.xrHelper_.baseExperience.sessionManager.onXRFrameObservable.addOnce(() => {
        // set the height at the first frame
        console.log(' 我走一路看')
        this.xrHelper_.baseExperience.camera.position.y += 1;
    })

    this.xrHelper_.input.onControllerAddedObservable.add((controller) => {
      controller.onMotionControllerInitObservable.add((motionController) => {
          if (motionController.handness === 'left') {
               const xr_ids = motionController.getComponentIds();
               console.log(xr_ids,'------------>')
               const triggerComponent = motionController.getComponent(xr_ids[0]);//xr-standard-trigger
               triggerComponent.onButtonStateChangedObservable.add((v) => {
                   console.log('xr-standard-trigger  0',v)
                //    this.handleMesh = null
                   if (triggerComponent.pressed) {
                 
                    this.handleMesh =this.scene.meshUnderPointer;
                    // 左边 摇杆
                            console.log( ' 能不能 拿到 物体',this.scene);
                   
                   }
               });
               const squeezeComponent = motionController.getComponent(xr_ids[1]);//xr-standard-squeeze
               squeezeComponent.onButtonStateChangedObservable.add(() => {
                console.log('xr-standard-squeeze  1',squeezeComponent.pressed)
             
               });
               const thumbstickComponent = motionController.getComponent(xr_ids[2]);//xr-standard-thumbstick
               thumbstickComponent.onButtonStateChangedObservable.add((v) => {console.log('xr-standard-thumbstick   2',v)
               console.log('xr-standard-thumbstick   2',squeezeComponent.pressed)
               });
               thumbstickComponent.onAxisValueChangedObservable.add((axes) => {  // 左手 手柄摇杆
                console.log(axes,'这个是什么玩意2')
               });

               const xbuttonComponent = motionController.getComponent(xr_ids[3]);//x-button
               xbuttonComponent.onButtonStateChangedObservable.add(() => {
                
                console.log('x-button   3',xbuttonComponent.pressed)
                 
               });
               const ybuttonComponent = motionController.getComponent(xr_ids[4]);//y-button
               ybuttonComponent.onButtonStateChangedObservable.add(() => { 
                
                console.log('y-button   4',ybuttonComponent.pressed)
              
               }); 
          }
          if (motionController.handness === 'right') {
               const xr_ids = motionController.getComponentIds();
               const triggerComponent = motionController.getComponent(xr_ids[0]);//xr-standard-trigger
               triggerComponent.onButtonStateChangedObservable.add(() => {
                // this.handleMesh = null
                   if (triggerComponent.pressed) {
                    this.handleMesh =this.scene.meshUnderPointer;
                    console.log('右手 点击 ',this.handleMesh)
                   
                   }
               });
               const squeezeComponent = motionController.getComponent(xr_ids[1]);//xr-standard-squeeze
               squeezeComponent.onButtonStateChangedObservable.add(() => {
                
               });
               const thumbstickComponent = motionController.getComponent(xr_ids[2]);//xr-standard-thumbstick
               thumbstickComponent.onButtonStateChangedObservable.add(() => {
               

               });
               thumbstickComponent.onAxisValueChangedObservable.add((axes) => {  // 右手 手柄摇杆
                console.log(axes,'这个是什么玩意1')
               });

               const abuttonComponent = motionController.getComponent(xr_ids[3]);//a-button
               abuttonComponent.onButtonStateChangedObservable.add(() => {
                 
               });
               const bbuttonComponent = motionController.getComponent(xr_ids[4]);//b-button
               bbuttonComponent.onButtonStateChangedObservable.add(() => {
                 
               });
             
          }

      })

  });

  }

}